/* eslint-disable */
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import {getToken} from './auth'

// Vue.prototype.$axios =
const http = axios.create({
    baseURL: process.env.BASE_API,
    timeout: 5000
})

http.interceptors.request.use(
    config => {
        if (store.getters.token) { // 如果有token，在header里面加入token
            config.headers['My-Token'] = getToken()
        }
        return config
    },
    error => {
        console.info(error)
        Promise.reject(error)
    }
)

http.interceptors.response.use(
    resopnse => {
        let data = resopnse.data
        
        if(data.code){
            Message({
                message: data.msg,
                type: 'error',
                duration: 3 * 1000
            })
            
            if(data.code < 1010){
                MessageBox.confirm('你已被登出，可以取消继续留在该页面，请重新登录', '确定登出', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('LogOut').then( () => {
                        location.reload() // 为了重新实例化vue-router对象 避免bug
                    })                   
                })
            }
            
            return Promise.reject('error')
        }else{
            return data
        }
    },
    error => {
        console.error("response err: " + error)
        return Promise.reject(error)
    }
)

export default http
